/*
 *
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: OptionOrderDetailActivity.java
 *   @Date: 1/28/19 9:00 PM
 *   @Author: chenjun
 *   @Description:
 *   @Copyright（C）: 2019 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 *
 */

package io.bhex.app.account.ui;

import android.support.annotation.NonNull;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.List;

import io.bhex.app.account.presenter.OptionOrderDetailPresenter;
import io.bhex.app.utils.NetWorkStatus;
import io.bhex.baselib.utils.ToastUtils;
import io.bhex.sdk.account.UserInfo;
import io.bhex.sdk.data_manager.AssetUtilsManager;
import io.bhex.sdk.data_manager.SymbolDataManager;
import io.bhex.app.R;
import io.bhex.sdk.trade.bean.OrderBean;
import io.bhex.sdk.trade.bean.OrderDealDetailResponse;
import io.bhex.app.account.presenter.OrderDetailPresenter;
import io.bhex.app.base.BaseActivity;
import io.bhex.baselib.constant.AppData;
import io.bhex.app.utils.DateUtils;
import io.bhex.app.utils.KlineUtils;
import io.bhex.app.utils.NumberUtils;

public class OptionOrderDetailActivity extends BaseActivity<OptionOrderDetailPresenter,OptionOrderDetailPresenter.OrderDetailUI> implements OptionOrderDetailPresenter.OrderDetailUI, BaseQuickAdapter.RequestLoadMoreListener{
    private SmartRefreshLayout swipeRefresh;
    private RecyclerView recyclerView;
    private View headerView;
    private OptionOrderDetailAdapter adapter;
    private TextView coinPair;
    private TextView buyMode;
    private TextView detailStatus;
    private TextView detailOrderPrice;
    private TextView detailOrderDealAveragePrice;
    private TextView detailOrderEntrustAmount;
    private TextView detailOrderDealAmount;
    private TextView detailOrderTotalDealMoney;
    private TextView detailOrderTotalFee;
    private List<OrderDealDetailResponse.DealOrderBean> currentOrderDatas=new ArrayList<>();
    private TextView detailOrderEntrustAmountTitle;
    private TextView priceMode;

    @Override
    protected int getContentView() {
        return R.layout.activity_order_detail_layout;
    }

    @Override
    protected OptionOrderDetailPresenter createPresenter() {
        return new OptionOrderDetailPresenter();
    }

    @Override
    protected OptionOrderDetailPresenter.OrderDetailUI getUI() {
        return this;
    }

    @Override
    protected void initView() {
        super.initView();
        swipeRefresh = viewFinder.find(R.id.swipeRefresh);
        swipeRefresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                refreshLayout.finishRefresh(1000);
                if (UserInfo.isLogin()) {
                    if (!NetWorkStatus.isConnected(OptionOrderDetailActivity.this)) {
                        ToastUtils.showShort(OptionOrderDetailActivity.this, getResources().getString(R.string.hint_network_not_connect));
                        return;
                    }
                    getPresenter().getDealDetail(false);
                }
            }
        });
        recyclerView = viewFinder.find(R.id.recyclerView);
        LayoutInflater layoutInflater = LayoutInflater.from(this);
        headerView = layoutInflater.inflate(R.layout.option_header_order_detail, null);
        coinPair = headerView.findViewById(R.id.detail_coinpair);
        buyMode = headerView.findViewById(R.id.detail_buymode);
        priceMode = headerView.findViewById(R.id.detail_price_mode);
        detailStatus = headerView.findViewById(R.id.detail_status);
        detailOrderPrice = headerView.findViewById(R.id.detail_order_price);
        detailOrderDealAveragePrice = headerView.findViewById(R.id.detail_order_deal_average_price);
        detailOrderEntrustAmountTitle = headerView.findViewById(R.id.detail_order_entrust_amount_title);
        detailOrderEntrustAmount = headerView.findViewById(R.id.detail_order_entrust_amount);
        detailOrderDealAmount = headerView.findViewById(R.id.detail_order_deal_amount);
        detailOrderTotalDealMoney = headerView.findViewById(R.id.detail_order_total_deal_money);
        detailOrderTotalFee = headerView.findViewById(R.id.detail_order_total_fee);


        adapter = new OptionOrderDetailAdapter(currentOrderDatas);
//            adapter.openLoadAnimation(BaseQuickAdapter.SCALEIN);
        adapter.isFirstOnly(false);
        adapter.setOnLoadMoreListener(this,recyclerView);
//            swipeRefresh.setColorSchemeColors(Color.RED, Color.BLUE, Color.GREEN);
//            swipeRefresh.setOnRefreshListener(this);
        adapter.addHeaderView(headerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        recyclerView.setAdapter(adapter);
    }

    @Override
    protected void addEvent() {
        super.addEvent();
    }


    @Override
    public void showHeaderOrders(OrderBean order) {
        try {

            coinPair.setText(order.getSymbolName());
            buyMode.setText(KlineUtils.getOptionBuyOrSellTxt(this, order.getSide()));
            buyMode.setTextColor(KlineUtils.getBuyOrSellColor(this, order.getSide()));
            detailStatus.setText(KlineUtils.getOrderStatus(this, order));
            priceMode.setText(KlineUtils.getPriceModeTxt(this, order.getType()));
            detailOrderPrice.setText(KlineUtils.getPrice(this, order));
            detailOrderDealAveragePrice.setText(KlineUtils.getAvgPrice(this, order));
            detailOrderEntrustAmountTitle.setText(KlineUtils.getEntrustTitle(this, order));
            int baseDigit = SymbolDataManager.GetInstance().getTokenDigitBySymbolIdAndTokenId(order.getSymbolId() + order.getBaseTokenId());
            detailOrderEntrustAmount.setText(NumberUtils.roundFormatDown(order.getOrigQty(), baseDigit) + " " + getString(R.string.string_option_unit));
            detailOrderDealAmount.setText(NumberUtils.roundFormatDown(order.getExecutedQty(), baseDigit) + " " + getString(R.string.string_option_unit));
            detailOrderTotalDealMoney.setText(KlineUtils.getDealMoney(this, order));
            double totalfees = 0d;
            if (order.getFees() != null) {
                for (OrderBean.FeesBean bean : order.getFees()) {
                    totalfees = NumberUtils.add(totalfees, Double.valueOf(bean.getFee()));
                }

                if(totalfees > 0)
                    detailOrderTotalFee.setText(totalfees + " " + order.getQuoteTokenName());
                else
                    detailOrderTotalFee.setText("0"  + " " + order.getQuoteTokenName());
            }
            else
                detailOrderTotalFee.setText("0"  + " " + order.getQuoteTokenName());
        }
        catch (Exception e){

        }
    }

    @Override
    public void loadMoreComplete() {
        if (adapter != null) {
            adapter.loadMoreComplete();
        }
    }

    @Override
    public void loadMoreFailed() {

    }

    @Override
    public void loadEnd() {
        if (adapter != null) {
            adapter.loadMoreEnd();
        }
    }

    @Override
    public void showOrders(List<OrderDealDetailResponse.DealOrderBean> datas) {
        if (datas != null) {
            currentOrderDatas = datas;
            adapter.setNewData(datas);
        }
    }

    @Override
    public void onLoadMoreRequested() {
        getPresenter().loadMore();
    }


    private class OptionOrderDetailAdapter extends BaseQuickAdapter<OrderDealDetailResponse.DealOrderBean,BaseViewHolder> {

        OptionOrderDetailAdapter(List<OrderDealDetailResponse.DealOrderBean> data) {
            super(R.layout.item_option_order_detail_layout, data);
        }

        @Override
        protected void convert(final BaseViewHolder baseViewHolder, final OrderDealDetailResponse.DealOrderBean itemModel) {
            baseViewHolder.setText(R.id.detail_order_deal_time, DateUtils.getSimpleTimeFormat(Long.valueOf(itemModel.getTime()), "HH:mm:ss yyyy/MM/dd"));
            int tokenDigit = SymbolDataManager.GetInstance().getTokenDigitBySymbolIdAndTokenId(itemModel.getSymbolId() + itemModel.getQuoteTokenId());
            int baseDigit = SymbolDataManager.GetInstance().getTokenDigitBySymbolIdAndTokenId(itemModel.getSymbolId() + itemModel.getBaseTokenId());
            int amountDigit = SymbolDataManager.GetInstance().getAmountDigitBySymbolIdAndTokenId(itemModel.getSymbolId() + itemModel.getQuoteTokenId());
            baseViewHolder.setText(R.id.detail_order_deal_price,  KlineUtils.roundFormatDown(itemModel.getPrice(),tokenDigit)+" "+itemModel.getQuoteTokenName());
            baseViewHolder.setText(R.id.detail_order_deal_amount, KlineUtils.roundFormatDown(itemModel.getQuantity(),baseDigit)+" "+getString(R.string.string_option_unit));
            baseViewHolder.setText(R.id.detail_order_deal_money, KlineUtils.roundFormatDown(String.valueOf(NumberUtils.mul(itemModel.getQuantity(),itemModel.getPrice())),amountDigit)+" "+itemModel.getQuoteTokenName());
            if (!TextUtils.isEmpty(itemModel.getFee())) {
                if (Double.valueOf(itemModel.getFee())>0) {
                    baseViewHolder.setText(R.id.detail_order_fee, KlineUtils.roundFormatDown(itemModel.getFee(),AppData.Config.DIGIT_DEFAULT_VALUE)+" "+itemModel.getFeeTokenName());
                }else{
                    baseViewHolder.setText(R.id.detail_order_fee, "0" + itemModel.getQuoteTokenName());
                }
            }else{
                baseViewHolder.setText(R.id.detail_order_fee,  "0" + itemModel.getQuoteTokenName());
            }

            baseViewHolder.setText(R.id.detail_order_position, KlineUtils.roundFormatDown(itemModel.getQuantity(),baseDigit)+" "+getString(R.string.string_option_unit));

        }

    }
}
